package com.zbdx.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;

@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private final String UPLOAD_DIRECTORY = "D:\\IDEAWorkSpace\\online-shopping\\web\\images";
    private final String DB_URL = "jdbc:mysql://localhost:3306/onlineshop?serverTimezone=GMT%2B8&characterEncoding=utf8&useUnicode=true&useSSL=false";
    private final String USER = "root";
    private final String PASS = "yang2532661314";
    private int count = 0;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (!ServletFileUpload.isMultipartContent(request)) {
            response.getWriter().println("Error: Form must has enctype=multipart/form-data.");
            return;
        }


        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        try {
            List<FileItem> formItems = upload.parseRequest(request);

            String PName = null;
            for (FileItem item : formItems) {
                if (item.isFormField() && item.getFieldName().equals("PName")) {
                    PName = item.getString("UTF-8");
                    break;
                }
            }

            if (PName == null) {
                response.getWriter().println("Error: PName is null.");
                return;
            }

            System.out.println("PName = " + PName);


            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = UPLOAD_DIRECTORY + File.separator + fileName;
                    String DfilePath = "images"+File.separator+fileName;
                    File storeFile = new File(filePath);
                    System.out.println(filePath);
                    System.out.println(DfilePath);

                    item.write(storeFile);

                    // 存储文件路径到数据库
                    count++;
                    if(count>3){
                        count = count%3;
                    }

                    System.out.println("count = "+count+" "+"PName = "+PName);
                    saveFilePathToDatabase(DfilePath,PName);
                }
            }
            response.sendRedirect("page/shopping/merchant/02_mygoods.jsp");
        } catch (Exception ex) {
            request.getSession().setAttribute("message", "There was an error: " + ex.getMessage());
        }
    }

    private void saveFilePathToDatabase(String filePath, String PName) {
        if(count == 1){
            try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
                 PreparedStatement pstmt = conn.prepareStatement("UPDATE product SET PImage01=? WHERE PName=?")) {

                pstmt.setString(1, filePath);
                pstmt.setString(2, PName);
                int affectedRows = pstmt.executeUpdate();

                if (affectedRows > 0) {
                    System.out.println("img1 path saved to database successfully.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (count == 2) {
            try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
                 PreparedStatement pstmt = conn.prepareStatement("UPDATE product SET PImage02=? WHERE PName=?")) {

                pstmt.setString(1, filePath);
                pstmt.setString(2, PName);
                int affectedRows = pstmt.executeUpdate();

                if (affectedRows > 0) {
                    System.out.println("img2 path saved to database successfully.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (count == 3) {
            try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
                 PreparedStatement pstmt = conn.prepareStatement("UPDATE product SET PImage03=? WHERE PName=?")) {

                pstmt.setString(1, filePath);
                pstmt.setString(2, PName);
                int affectedRows = pstmt.executeUpdate();

                if (affectedRows > 0) {
                    System.out.println("img3 path saved to database successfully.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}